package com.shuai.jit.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuai.jit.entity.user.Permission;
import com.shuai.jit.entity.user.User;
import com.shuai.jit.entity.vo.VoUser;
import com.shuai.jit.mapper.PermissionMapper;
import com.shuai.jit.mapper.UserMapper;
import com.shuai.jit.utils.JwtUtil;
import com.shuai.jit.utils.NoteUtil;
import com.shuai.jit.utils.RandomString;
import com.shuai.jit.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {


    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    PermissionMapper permissionMapper;


    @Autowired
    JwtUtil jwtUtil;

    @Override
    public VoUser getInfo(String username) {
        User user=this.baseMapper.selectByName(username);
        if(user!=null){
            VoUser voUser=new VoUser();
            try {
                PropertyUtils.copyProperties(voUser,user);
            } catch (Exception e){
                return null;
            }
            return voUser;
        }
        return null;
    }

    @Override
    public String loginTelephoneCode(String telephone, String code) {
        log.info("telephone"+telephone);
        User user=this.baseMapper.selectByTelephone(telephone);
        if(user!=null){
            log.info(user.toString());
            String co= String.valueOf(redisTemplate.opsForValue().get(telephone)) ;
            if(co!=null&&co.equals(code)){
                List<String> authorityList = new ArrayList<>();
                // 这里读取权限表，然后查看
                // 根据用户的等级，获取全部的权限
                List<Permission> permissions=permissionMapper.selectByLev(user.getUserLev());
                // 添加路径
                for (Permission p:permissions){
                    authorityList.add(p.getPath());
                }
//                log.info(permissions.toString());
                // 设置权限
                redisTemplate.opsForValue().set(user.getUsername(),authorityList);
                // 生产token
                return jwtUtil.sign(user.getUsername());
            }else {
                return null;
            }
        }
        return null;
    }

    @Override
    public Integer loginNumberPassword(String number, String password) {
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.eq("number",number);
        User user=this.baseMapper.selectOne(userQueryWrapper);
        if(user!=null){
            BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
            // 从 密码正确
            if(encoder.matches(password+user.getSalt(),user.getPassword())){
               return 1;
            }else {
                return -2;
            }
        }else{
            return -1;
        }
    }

    @Autowired
    NoteUtil noteUtil;

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @Override
    public String send(String phone) {
        return noteUtil.sendSms(phone);
    }

    @Override
    public User loginTelephone(String telephone, String password) {
        User user=this.baseMapper.selectByTelephone(telephone);
        if(user!=null){
            if(new BCryptPasswordEncoder().matches(password+user.getSalt(),user.getPassword())){
                return user;
            }
        }
        return null;
    }

    /**
     * 需要登录的用户
     * @param user
     * @return
     */
    @Override
    public Integer register(User user) {
        if(user==null||user.getUserTelephone()==null||user.getUsername()==null){
            return -3;
        }
        User temp=this.baseMapper.selectRegister(user.getUserTelephone(),user.getUsername());
        if(temp!=null){
            return -1;
        }
        String redisCode= stringRedisTemplate.opsForValue().get(user.getUserTelephone());

         if(!redisCode.equals(user.getCode())){
            return -2;
         }
        String salt= RandomString.getRandomString(10);
        user.setSalt(salt);
        user.setUserLev(0);

        if(user.getLevName()!=null){
            if(user.getLevName().equals("学生")){
                user.setUserLev(1);
            }
            if(user.getLevName().equals("教师")){
                user.setUserLev(2);
            }
        }

        // 刚注册用户为 0
        user.setApprove(0);
        user.setUserIntroduce("新用户，啥也没写");
        user.setUserImg("https://jokerak.oss-cn-beijing.aliyuncs.com/avatar");
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()+salt));
        return this.baseMapper.insert(user);
    }
}
